<?php namespace App\Http\Controllers;


use App\District;
use App\Exceptions\HomeException;
use App\Exceptions\NotFoundException;
use App\Exceptions\SecurityException;
use App\Http\Controllers\Api\UserController;
use App\Investor;
use App\InvestOrg;
use App\InvestOrgInfo;
use App\Phases;
use App\ProjectTeam;
use App\ProjectUrl;
use App\Roles;
use App\Services\MessageManager;
use App\UserCreate;
use App\UserTeams;
use App\UserWork;
use Illuminate\Auth\Guard;
use Illuminate\Http\Request;
use App\Project;
use App\User;
use App\Fields;
use App\UserInfo;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\View;


class HomeController extends Controller
{

    public $request;
    public $pageSize = 1;

    function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }



    /** 首页显示 */
    public function index()
    {
        return view('home');
    }

    /** 登录页面的显示 */
    public function loginShow(){
        return view('auth.login');
    }

    /** 注册页面显示 */
    public function registerShow(){
        return view('auth.register');
    }

    /** 注销页面 */
    public function signOut(Guard $guard)
    {
        $guard->logout();
        return redirect(route('Home'));
    }

    /**==============================START 创业者===============================*/

    /** 创业者展示页面 */
    public function enterpriser(){
        $users = User::whereRole(0)->whereStatus(1)->paginate(self::PAGE);
        $roles = Roles::all();

        return view('creater.enterpriser',array('users'=>$users , 'roles'=>$roles));

    }

    /** 创业者详细信息页面 */
    public function enterpriserDetails($userId){

        $user = User::whereId($userId)->whereStatus(1)->first();

        return view('creater.enter_details' , array('user' => $user , 'userId'=>$userId));
    }
    /**-----------------------------END 创业者--------------------------------*/

    /**==============================START 项目===============================*/

    /**
     * 通过id获取项目详细信息
     * @param $id
     * @return mixed|static
     */
    public function getProjectById($id)
    {
        $project = Project::whereProjectAuth(1)->find($id);
        if(!$project)
            return view('errors.404');
        return view('project.project_detail' , array('project'=>$project,'user'=>$project->toUser,'userInfo'=>$project->toUser->userInfo));
    }

    /**
     * 项目列表
     * @return View
     */
    public function  getProjectPage()
    {
        $projects   = Project::whereProjectAuth(1)->paginate(self::PAGE);
        $phases     = Phases::all();
        $fields     = Fields::all();
        $district   = District::all();

        $data = array(
            'projects'=> $projects ,
            'phases'    => $phases,
            'fields'    => $fields,
            'districts' => $district
        );

        return view('project.projects' ,$data);
    }

    public function showProjectBySearch()
    {
        $keyword = Input::get('keyword');
        $stage   = Input::get('stage');
        $phase   = Input::get('phase');
        $field   = Input::get('field');
        $dist    = Input::get('dist');

        $stage_key = !is_null($stage) ? $stage : '';
        $phase_key = !is_null($phase) ? $phase : '';
        $field_key = !is_null($field) ? $field : '';
        $dist_key  = !is_null($dist) ? $dist : '';

        $projects   = Project::whereProjectAuth(1);
        if($stage)
            $projects = $projects->like('is_finance',$stage);

        if($phase)
            $projects = $projects->like('phase_id',$phase);

        if($field)
            $projects = $projects->like('field_id',$field);

        if($dist)
            $projects = $projects->like('city',urldecode($dist));

        $projects   = $projects->get();
        $phases     = Phases::all();
        $fields     = Fields::all();
        $district   = District::all();

        $data = array(
            'projects'=> $projects ,
            'phases'    => $phases,
            'fields'    => $fields,
            'districts' => $district,
            'keyword'   => array('stage_key'=>$stage_key,'phase_key'=>$phase_key,'field_key'=>$field_key,'dist_key'=>$dist_key),
        );

        return view('project.project-search' ,$data);

    }

    /**
     * 15天快速融资列表
     * @return View
     */
    public function get15FinancePage()
    {
        $projects   = Project::whereProjectAuth(1)->whereIsFinance(1)->paginate(10);
        $phases     = Phases::all();
        $fields     = Fields::all();

        if($projects)
            return view('project.projects' , array('projects'=>$projects , 'phases'=>$phases , 'fields'=>$fields));

    }

    /**
     * 显示创建项目页
     * @param Guard $guard
     * @return View
     */
    public  function showCreateProject(Guard $guard)
    {
        if($guard->guest())
            return redirect(route('Home.Auth.loginShow'));

        $fields = Fields::all();
        $projectTeams = UserTeams::whereUserId($guard->user()->id)->get();
        return view('project.create-project',array('fields'=>$fields,'projectTeams'=>$projectTeams));
    }

    public function showCreateProjectNeed(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $id = Session::get('projectId');
        $projectId = !is_null($id) ? $id : -1;
        /** @var User $user */
        $user = $guard->user();
        $userInfo = $user->userInfo;
        return view('project.create-need',array('user'=>$user,'userinfo'=>$userInfo,'projectid'=>$projectId));
    }

    /**-----------------------------END 项目-----------------------------------*/

    /**==============================START 投资人===============================*/

    /**
     *  通过投资人标识 获取投资人信息
     * @param $userId
     * @return View
     * @throws HomeException
     */
    public function getInvestorByUserId($userId)
    {
        if(User::whereId($userId)->exists()) {
            $user = User::find($userId);
            $investor = UserInfo::whereUserId($userId)->first();
            return view('investor.investor_detail', array('userId' => $userId, 'investor' => $investor, 'user' => $user));
        }else{
            throw new HomeException(HomeException::NoData);
        }
    }

    /**
     * 分页显示投资者信息
     * @return $this
     */
    public function getInvestorPage()
    {
        $investors = User::whereRole(1)->whereStatus(1)->paginate(self::PAGE);
        $fields = Fields::all();
        $phases = Phases::all();

        return view('investor.investor' , array('investors'=>$investors , 'fields'=>$fields , 'phases'=>$phases));
    }

    public function getInvestorInvProjectMoreByUserId()
    {
        return view('investor.inv-pages');
    }

    /**-----------------------------END 投资人--------------------------------*/

    /**==============================START 投资机构===========================*/

    /**
     *  通过投资机构id 获取信息
     * @param $id
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function getInvestOrgDetails($id)
    {
        $investOrg = InvestOrg::find($id);
        if($investOrg)
            return view('investorg.investorg_details' , array('org'=>$investOrg ));
    }

    /**显示投资机构信息
     * @return View
     */
    public function getInvestOrg()
    {
        $investOrg = InvestOrg::paginate(self::PAGE);
        $fields = Fields::all();
        $phases = Phases::all();

        return view('investorg.investorg' , array('investOrg'=>$investOrg , 'fields'=>$fields , 'phases'=>$phases));
    }

    public function investorg(){
        return view('investorg.investorg_details');
    }

    public function getOrgInvProjectMoreByUserId()
    {
        return view('investorg.org-pages');
    }
    /**-----------------------------END 投资机构--------------------------------*/

    /**==============================START 用户中心===========================*/

    public function userCenter(Guard $guard)
    {
        /** 判断用户是否登录 */
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $userId = $guard->user()->id;
        /** @var User $user */
        $user   = $guard->user();

        //用户信息
        $userInfo   = UserInfo::whereUserId($userId)->first();
        //角色
        $roles = Roles::all();
        $user_role = null;
        if($userInfo)$user_role = $userInfo->user_x_roles()->get();
        $user_create = UserCreate::whereUserId($userId)->get();
        $user_work   = UserWork::whereUserId($userId)->get();

        $projects = Project::whereUserId($userId)->get();

        if($user_role !== null) {
            foreach ($roles as $role) {
                foreach ($user_role as $u_role) {
                    if ($role->id == $u_role->id) {
                        $role['checked'] = 'checked';
                    }
                }
            }
        }

        $userFocusProjects   = $user->userFocusProject()->get();
        $userFocusInvestors  = $user->userFocusInvestor()->get();
        $userFocusInvestorgs = $user->userFocusInvestOrg()->get();

        $messages = MessageManager::getMessage($userId);

        return view('user.user-center' , array(
            'user'                => $user,
            'userInfo'            => $userInfo,
            'roles'               => $roles,
            'user_roles'          => $user_role,
            'user_creates'        => $user_create,
            'user_works'          => $user_work,
            'projects'            => $projects,
            'userFocusProjects'   => $userFocusProjects,
            'userFocusInvestors'  => $userFocusInvestors,
            'userFocusInvestorgs' => $userFocusInvestorgs,
            'messages'            => $messages,
        ));
    }

    public function showProjectBase(Guard $guard,$projectId)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */
        $user = $guard->user();

        /** @var Project $project */
        $project = Project::whereUserId($user->id)->whereId($projectId)->first();
        $fields = Fields::all();

        $project_fileds = null;
        if($project)$project_fileds = $project->project_x_fields()->get();

        if($project_fileds !== null){
            foreach($fields as $field){
                foreach($project_fileds as $project_filed){
                    if($field->id == $project_filed->id){
                        $field['checked'] = 'checked';
                    }
                }
            }
        }

        $project_urls = ProjectUrl::whereProjectId($projectId)->get();

        if(!$project)
            throw new NotFoundException(NotFoundException::ProjectNotFound);

        return view('user.project-base',array('project'=>$project,'fields'=>$fields,'project_urls'=>$project_urls));
    }

    public function showProjectInfo(Guard $guard,$projectId)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */
        $user = $guard->user();
        /** @var Project $project */
        $project = Project::whereUserId($user->id)->whereId($projectId)->first();
        $project_url = ProjectUrl::whereProjectId($projectId)->whereUrlType('web')->first();

        $fields = Fields::all();
        $project_fileds = null;
        if($project)$project_fileds = $project->project_x_fields()->get();

        if($project_fileds !== null){
            foreach($fields as $field){
                foreach($project_fileds as $project_filed){
                    if($field->id == $project_filed->id){
                        $field['checked'] = 'checked';
                    }
                }
            }
        }

        $projectTeams = $project->project_x_team()->get();

        return view('user.project-info',array(
            'project'      => $project,
            'project_url'  => $project_url,
            'fields'       => $fields,
            'projectTeams' => $projectTeams
        ));
    }

    public function test(){
        return view('project.test');
    }

    /**
     * 获取后台登录页面
     * @return \Illuminate\View\View
     */
    public function showAdminSignIn()
    {
        return view('admin.Login');
    }

    /**-----------------------------strart  15天快速融资--------------------------------*/

    /**
     * 15天快速融资页面显示
     * @return View
     */
    public function Show15Finance()
    {
        return view('15finance.15finance');
    }


    /**-----------------------------END 天快速融资--------------------------------*/

}
